#include "grid.h"

grid::grid()
{
    //block_board initialization;
    for(int i=0; i<GRID_HEIGHT; i++)
    {
        for(int j=0; j<GRID_WIDTH; j++)
        {
            block_board[i][j].full=false;
            block_board[i][j].color=0;
        }
    }

    //actual pile height initialization
    pile_height = 0;

}

grid::~grid()
{
    //dtor
}

void grid::Set_board_pos(int row, int column, bool value, int color)
{
    block_board[row][column].full=value;
    block_board[row][column].color=color;
}

//Used to check if a line is full and must be ereased
bool grid::check_line(int line)
{
    //if any of the blocks in the grid is empty the line is not complete
    for(int i=0; i<GRID_WIDTH; i++)
    {
        if(!block_board[line][i].full)
            return false;
    }

    return true;
}

void grid::move_lines(int line)
{
    //Move lines down
    for(int i=0;i<(pile_height-line+1);i++)
    {
        for(int j=0;j<GRID_WIDTH;j++)
        {
            if((line+i+1)<GRID_HEIGHT)
                block_board[line+i][j] = block_board[line+i+1][j];
            else
                block_board[line+i][j].full = false;
        }

    }
}

//Used to clean the lines after each block is positioned
int grid::clean_lines()
{
    int num_lines = 0;

    //check every line and save its status
    for(int i=0; i<=pile_height; i++)
    {
        //If the line is full
        if(check_line(i))
        {
            move_lines(i);
            i--; //Continue with the same line
            num_lines++; //update number of lines
        }
    }

    return num_lines;

}

void grid::clear_grid()
{
    //Empty game board
    for(int i=0; i<GRID_HEIGHT; i++)
    {
        for(int j=0; j<GRID_WIDTH; j++)
        {
            block_board[i][j].full=false;
            block_board[i][j].color=0;
        }
    }

    //Restart pile height
    pile_height = 0;
}
